import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:jump_scape/js_ui/js_dialog/js_game.dart';
import 'package:jump_scape/js_ui/js_widget/js_image_view.dart';
import 'package:jump_scape/js_ui/js_widget/js_text_ghosting_view.dart';

import '../../js_data/js_event.dart';
import '../../js_data/js_game.dart';
import '../js_widget/js_game.dart';
import '../js_widget/js_style.dart';

class JsGameActivity extends StatefulWidget {
  static const url = 'game';
  final int index;
  const JsGameActivity({super.key, required this.index});

  @override
  State<StatefulWidget> createState() => _JsGameActivity();
}

class _JsGameActivity extends State<JsGameActivity> with WidgetsBindingObserver {
  var isShowGameTips = true;
  var isRunningGame = false;
  var isStarted = true;

  Timer? timer;
  int time = 0; // 毫秒
  String timeString = "00:00:00"; // 格式化的时间字符串

  final gameController = GameController();

  @override
  void initState() {
    super.initState();
    JsEventManager.statPage(page: JsEventName.jsNameGame);

    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    timer?.cancel();
    pauseGame();
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);
    switch (state) {
      case AppLifecycleState.resumed:
        debugPrint("[lifecycle] Application entry foreground======");
        break;
      case AppLifecycleState.paused:
        debugPrint("[lifecycle] Application enter background======");
        if (isRunningGame) {
          isStarted = false;
          setState(() {});
          pauseGame();
        }
        break;
      default:
        debugPrint("[lifecycle] state=$state");
        break;
    }
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () => Future.value(false),
      child: Scaffold(
        body: Stack(
          children: [
            jsImage('assets/image/ic_game_bg_${widget.index + 1}.png', width: double.infinity, height: double.infinity, fit: BoxFit.cover),
            SimpleRunningGame(
              controller: gameController,
              onGameOver: () {
                gameFailure();
              },
            ),
            pauseState(),
            Padding(
              padding: EdgeInsets.only(top: ScreenUtil().statusBarHeight),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.end,
                children: [
                  InkWell(
                    onTap: () {
                      if (Navigator.canPop(context)) {
                        Navigator.pop(context);
                      }
                    },
                    child: Container(
                      padding: EdgeInsets.fromLTRB(18.r, 15.r, 18.r, 0),
                      child: jsImage(widget.index == 1 ? 'assets/image/ic_finish_2.png' : 'assets/image/ic_finish.png', width: 64.r, height: 64.r),
                    ),
                  ),
                  Expanded(
                    child: Padding(
                      padding: EdgeInsets.only(left: 24, right: 22.r, bottom: 2.r),
                      child: Stack(
                        children: [
                          jsImage(
                              widget.index == 1
                                  ? 'assets/image/ic_game_status_bg_2.png'
                                  : widget.index == 2
                                      ? 'assets/image/ic_game_status_bg_3.png'
                                      : 'assets/image/ic_game_status_bg.png',
                              fit: BoxFit.fitWidth),
                          Positioned.fill(
                            child: Row(
                              children: [
                                SizedBox(width: 36.r),
                                Expanded(child: timerText()),
                                InkWell(
                                  child: (isRunningGame && !isStarted) ? jsImage('assets/image/ic_game_resume_${widget.index + 1}.png', width: 28.r, fit: BoxFit.fitWidth) : jsImage(widget.index == 2 ? 'assets/image/ic_game_pause_2.png' : 'assets/image/ic_game_pause.png', width: 28.r, fit: BoxFit.fitWidth),
                                  onTap: () {
                                    if (isRunningGame) {
                                      isStarted = !isStarted;
                                      setState(() {});

                                      if (isStarted) {
                                        startGame(isRestart: false);
                                      } else {
                                        pauseGame();
                                      }
                                    }
                                  },
                                ),
                                SizedBox(width: 32.r),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ),
                ],
              ),
            ),
            Align(alignment: Alignment.topCenter, child: gameTips()),
          ],
        ),
      ),
    );
  }

  Widget timerText() {
    final text = timeString;

    if (widget.index == 2) {
      return Stack(
        alignment: Alignment.center,
        children: [
          Text(
            text,
            style: jsTextStyle(
              font: JsTextFont.EricaOne,
              fontColor: Colors.white,
              fontSize: 20.r,
              shadows: [Shadow(offset: Offset(0, 4.r), blurRadius: 4.r, color: Colors.black.withOpacity(0.25))],
            ),
          ),
          Text(
            text,
            style: jsTextStyle(
              font: JsTextFont.EricaOne,
              fontSize: 20.r,
              foreground: Paint()
                ..style = PaintingStyle.stroke
                ..strokeWidth = 1.r
                ..color = Color(0xFFEF55AC),
            ),
          ),
        ],
      );
    }
    return Text(
      text,
      style: jsTextStyle(
        font: JsTextFont.EricaOne,
        fontColor: Colors.white,
        fontSize: 20.r,
        shadows: [Shadow(offset: Offset(0, 4.r), blurRadius: 4.r, color: Colors.black.withOpacity(0.25))],
      ),
    );
  }

  Widget gameTips() {
    if (!isShowGameTips) return SizedBox(width: 0, height: 0);

    return Container(
      margin: EdgeInsets.only(top: ScreenUtil().statusBarHeight + 116.r),
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          jsImage('assets/image/ic_game_first_tips_bg.png', height: 402.r, fit: BoxFit.fitHeight),
          jsImage('assets/gif/ic_game_first_tips.gif', height: 83.r, fit: BoxFit.fitHeight, padding: EdgeInsets.only(top: 127.r)),
          Positioned(
            left: 0,
            top: 217.r,
            right: 0,
            child: Text('"Tap to jump\nand avoid the pits!"', textAlign: TextAlign.center, style: jsTextStyle(font: JsTextFont.PoetsenOne, fontColor: Color(0xFF3B0C27), fontSize: 22.r, height: 30.0 / 22)),
          ),
          Positioned(
            left: 28.r,
            right: 28.r,
            bottom: 21.r,
            child: InkWell(
              child: Container(
                clipBehavior: Clip.antiAlias,
                decoration: jsShapeRound(radius: 12.r, shadows: [
                  BoxShadow(offset: Offset(0, 2.r), blurRadius: 2.r, color: Colors.black.withOpacity(0.25)),
                ]),
                child: Stack(
                  alignment: Alignment.center,
                  children: [
                    jsImage('assets/image/ic_game_start_bg.png', fit: BoxFit.fitWidth),
                    JsTextGhostingView(
                      'start',
                      fontSize: 24.r,
                      fontForegroundColor: Colors.white,
                      fontBackgroundColor: Color(0xFFFF3099),
                      fontBorderColor: Color(0xFFFF9BCB),
                      strokeWidthScale: 1.5,
                    ),
                  ],
                ),
              ),
              onTap: () async {
                if (isRunningGame) return;

                isRunningGame = true;
                isShowGameTips = false;
                isStarted = true;
                time = 0;
                timeString = "00:00:00";

                setState(() {});

                startGame(isRestart: true);

                // final setting = await JsObjectBox.setting;
                // var member = JsObjectBox.memberBox.query(MemberBox_.userId.equals(setting.userId)).build().findFirst();
                // if (member != null) {
                //   if (member.gameCount > 0) {
                //     member.gameCount -= 1;
                //     JsObjectBox.memberBox.put(member);

                //     setState(() {});

                //     startGame();
                //   } else {
                //     // TODO：购买游戏次数
                //     isRunningGame = false;
                //   }
                // }
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget pauseState() {
    if (!isRunningGame || isStarted) return SizedBox(width: 0, height: 0);

    return InkWell(
      child: Container(
        width: double.infinity,
        height: double.infinity,
        color: Colors.black.withOpacity(0.5),
        alignment: Alignment.center,
        child: InkWell(
          child: Container(
            width: 106.r,
            height: 106.r,
            clipBehavior: Clip.antiAlias,
            decoration: jsShapeRound(radius: 53.r),
            child: jsImage('assets/image/ic_game_resume_big.png'),
          ),
          onTap: () {
            isStarted = true;

            setState(() {});

            startGame(isRestart: false);
          },
        ),
      ),
      onTap: () {},
    );
  }

  void startGame({required bool isRestart}) {
    if (isRestart) {
      gameController.restartGame();
    } else {
      gameController.resumeGame();
    }

    timer = Timer.periodic(Duration(milliseconds: 33), (timer) {
      if (isStarted) {
        time += 33;
        timeString = formatTime(time);

        setState(() {});
      }
    });
  }

  void pauseGame() {
    gameController.pauseGame();

    timer?.cancel();
    timer = null;
  }

  void gameFailure() {
    isRunningGame = false;
    isStarted = true;

    setState(() {});

    pauseGame();

    jsShowGameFailureDialog(context, onRestart: () {
      isShowGameTips = true;
      time = 0;
      timeString = "00:00:00";
      setState(() {});
    });

    if (widget.index == 0) {
      JsGame().createGameRecordSpring(time: time);
    } else if (widget.index == 1) {
      JsGame().createGameRecordWinter(time: time);
    } else if (widget.index == 2) {
      JsGame().createGameRecordCity(time: time);
    }
  }

  String formatTime(int milliseconds) {
    int hours = milliseconds ~/ (60 * 60 * 1000);
    int minutes = (milliseconds % (60 * 60 * 1000)) ~/ (60 * 1000);
    int seconds = (milliseconds % (60 * 1000)) ~/ 1000;
    int ms = (milliseconds % 1000) ~/ 10; // 毫秒取两位数

    if (hours > 0) {
      return '${_twoDigits(hours)}:${_twoDigits(minutes)}:${_twoDigits(seconds)}';
    } else {
      return '${_twoDigits(minutes)}:${_twoDigits(seconds)}:${_twoDigits(ms)}';
    }
  }

  String _twoDigits(int n) => n.toString().padLeft(2, '0');
}
